package com.zdya.combatdocuments.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zdya.combatdocuments.entity.Network;
import com.zdya.combatdocuments.entity.NetworkUser;
import com.zdya.combatdocuments.entity.User;
import com.zdya.combatdocuments.entity.vo.ResultVo;
import com.zdya.combatdocuments.mapper.NetworkUserMapper;
import com.zdya.combatdocuments.mapper.UserMapper;
import com.zdya.combatdocuments.p2pNetwork.NodeUtil;
import com.zdya.combatdocuments.p2pNetwork.P2pClientBrowser;
import com.zdya.combatdocuments.service.NetworkService;
import com.zdya.combatdocuments.util.DmcUtils;
import com.zdya.combatdocuments.util.EthRPCUtil;
import com.zdya.combatdocuments.util.ResultVoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/documents/network")
public class NetworkController {

    @Autowired
    private NetworkService networkService;
    @Autowired
    private P2pClientBrowser p2pClientBrowser;
    @Autowired
    private NodeUtil nodeUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private NetworkUserMapper networkUserMapper;

    /**
     * 创建网络
     * @return
     */
    @GetMapping("/createNet")
    public ResultVo createNet(@RequestParam("name")String name,@RequestParam("userId")Long userId,@RequestParam(required = false, value = "gradeName")String gradeName,@RequestParam(required = false, value = "gradeTime")Long gradeTime,
                              @RequestParam(required = false, value = "firstLimittime")Long firstLimittime,@RequestParam(required = false, value = "secondLimittime")Long secondLimittime,@RequestParam(required = false, value = "thirdLimittime")Long thirdLimittime){
        ResultVo result = networkService.createNet(name, userId,gradeName,gradeTime,firstLimittime,secondLimittime,thirdLimittime);
        return result;
    }

    /**
     * 启动网络

     * @return
     */
    @GetMapping("/startNet")
    public ResultVo starNet(@RequestParam("netName")String netName,@RequestParam("createName")String createName){
        ResultVo result = networkService.starNet(netName,createName);
        return result;
    }

    /**
     * 加入网络
     * @param ipAddress 启动网络的主节点ip
     *        networkId 网络id
     *        userId    用户id
     * @return
     */
    @GetMapping("/joinNet")
    public ResultVo joinNet(@RequestParam("ipAddress") String ipAddress,@RequestParam("userId")Long userId){
        ResultVo result = networkService.joinNet(ipAddress, userId);
        return result;
    }

    /**
     * 获取用户相关网络列表
     * @param userId
     * @return
     */
    @GetMapping("/getNetList")
    public ResultVo getNetList(@RequestParam("userId")Long userId){
        List<Network> netList = networkService.getNetList(userId);
        return ResultVoUtil.success(netList);
    }


    @GetMapping("/getByPostNet")
    public String getByPostNet(@RequestParam("address")String address) throws Exception {
        Network network = nodeUtil.getLocalNetwork();

        List<NetworkUser> networkUsers = networkUserMapper.selectList(new LambdaQueryWrapper<NetworkUser>().eq(NetworkUser::getNetworkId, network.getId()));
        List<User> userList = new ArrayList<>();
        for(NetworkUser networkUser:networkUsers){
            User user = userMapper.selectById(networkUser.getUserId());
            userList.add(user);
        }
        network.setUserList(userList);
        //获取主节点信息
        String enodes = EthRPCUtil.getEnodes("127.0.0.1");
        network.setEnode(enodes);
        network.setSystemCurrentTime(System.currentTimeMillis());
        return JSONUtil.toJsonStr(network);
    }

    /**
     * 收到对方User，返回自身User
     * @param user
     * @return
     */
    @PostMapping("/changeUser")
    public String changeUser(@RequestBody User user){
        String result = networkService.changeUser(user);
        return result;
    }

    /**
     * 获取加入网络ip前缀
     * @return
     */
    @GetMapping("/getJoinNetIp")
    public ResultVo getJoinNetIp(){
        try{
            JSONObject jsonObject = new JSONObject(DmcUtils.getIpAndGateway().get(0));
            String ip = jsonObject.getStr("ip");
            int dotIndex = ip.lastIndexOf(".")+1;
            String substring = ip.substring(0, dotIndex);
            return ResultVoUtil.success(substring);
        }catch (Exception e){
            return ResultVoUtil.error("");
        }
    }


    /**
     * 浏览器client建联
     * @return
     */
    @GetMapping("/openBrowser")
    public ResultVo openBrowser(){
        p2pClientBrowser.connectPeer();
        return ResultVoUtil.success("ok");
    }

    /**
     * 发送消息
     * @return
     */
    @PostMapping("/sendMsg")
    public ResultVo sendMsg(String content,String id,Integer type){
        JSONObject jsonObject = new JSONObject();//聊天框信息格式
        jsonObject.put("content",content); //文本内容
        jsonObject.put("id",id);//接收方ip
        jsonObject.put("type",type);//文本类型--0
        p2pClientBrowser.write(p2pClientBrowser.getWebSocket(),jsonObject.toString());
        return ResultVoUtil.success("ok");
    }



}
